# For GDScript, use the global variable Dialogue.queue_text("Text to display here").
# For C#, use Node diag = GetNode("/root/Dialogue"); and then diag.Call("queue_text", "text")
extends CanvasLayer

const char_read_rate = 0.1
export var is_printing_text = false;

onready var textbox_cont = $TBoxContainer
onready var ar_label = $TBoxContainer/MarginContainer/HBoxContainer/ALabel
onready var label = $TBoxContainer/MarginContainer/HBoxContainer/Label

enum State {
	READY,
	READING,
	FINISHED
}

var current_state = State.READY
var text_queue = []

func _ready():
	print("State start: State.READY")
	hide_textbox()	
	# queue_text("really really long text")

func _process(_delta):
	match current_state:
		State.READY:
			if (!text_queue.empty()):
					display_text()

		State.READING:

			if(GameManager.isArabic && ar_label._get_current_chars() == 0): change_states(State.FINISHED)
			
			if(Input.is_action_just_pressed("ui_skiptext")): 
				label.percent_visible = 1.0
				if(GameManager.isArabic && ar_label._get_current_chars() != 0): ar_label._skip_ar_text()
				

				$Tween.stop_all()
				change_states(State.FINISHED)

		State.FINISHED:
			if (Input.is_action_just_pressed("ui_accept")):
				change_states(State.READY)
				hide_textbox()
				

				# Add cooldown after interaction is over only if the dialogue branch is empty.
				if(text_queue.empty()):
					yield(get_tree().create_timer(0.05), "timeout")
					GameManager.canInteract = true;

func queue_text(next_text):
	text_queue.push_back(next_text)
	
func queue_ar_text(next_ar_text):
	text_queue.push_back(next_ar_text)

func hide_textbox():
	label.text = ""
	ar_label.arabic_input = " "
	textbox_cont.hide()
	if(text_queue.empty()): is_printing_text = false
	ar_label.percent_visible = 0.0

func show_textbox():
	textbox_cont.show()
	is_printing_text = true

func display_text():
	if(GameManager.isArabic): ar_label.percent_visible = 1.0
	var next_txt = text_queue.pop_front()

	if(!GameManager.isArabic):
		label.text = next_txt
		label.percent_visible = 0.0
	else:
		ar_label.arabic_input = next_txt
		#ar_label.percent_visible = 0.0
	
	change_states(State.READING)

	if(!GameManager.isArabic):
		label.show()
	else:
		ar_label.show()

	show_textbox()

	if(!GameManager.isArabic):
		$Tween.interpolate_property(label, "percent_visible", 0.0, 1.0,
		len(next_txt) * char_read_rate, Tween.TRANS_LINEAR, Tween.EASE_IN_OUT)
		$Tween.start()
	else:
		ar_label._set_arabic_animation(next_txt)

func _on_Tween_tween_all_completed():
	change_states(State.FINISHED)

func change_states(next_state):
	current_state = next_state
	match current_state:
		State.READY:
			print("State changing to State.READY")
		State.READING:
			print("State changing to State.READING")
		State.FINISHED:
			print("State changing to State.FINISHED")



